﻿using mediaControl.Event;
using mediaControl.Utils;
using mediaControl.Views;
using mediaControl.Vo;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Application = System.Windows.Application;
using ListView = System.Windows.Controls.ListView;
using ListViewItem = System.Windows.Controls.ListViewItem;
using MessageBox = System.Windows.Forms.MessageBox;

namespace mediaControl.ViewModels
{

    public class ProgramListViewModel : BindableBase
    {
        //事件聚合器
        private readonly IEventAggregator _eventAggregator;

        private ObservableCollection<ProgramVo> programVos;

        private readonly IDialogService dialogService;

        private IContainerExtension _containerExtension;

        private ProgramItemVo selectedItem;

        private ObservableCollection<ProgramItemVo> currentList = new ObservableCollection<ProgramItemVo>();

        private string currentMusic;

        private int selectedIndex = -1;

        private int currentIndex = 0;

        private string musicSrc;

        private double startWith = 0;

        private int maxValue;

        private double volume = 0;

        private double endWith;

        private ProgramItemVo currentProgram;

        private MediaElement music;

        private string currentTimeStr;

        private string cycleMode = "0";

        private bool isPause = false;

        private string playText = "播放";

        private string switchMode;

        private int switchTime = 5;

        private int switchOutTime = 5;

        private bool isEnabled = true;

        private bool isPauseEnabled = true;

        //播放模式索引下标
        private int cycleIndex = 0;

        private double testVolume;

        private string currentMusicId;

        private string fileFullPath;

        private List<string> openScreenIds;

        private bool volumeEnable = false;

        private bool checkBoxEnable = false;

        private bool isDisplay = true;

        private List<Window> sourceWindowList = new List<Window>();

        private List<MonitorVo> monitorVos = new List<MonitorVo>();

        private ObservableCollection<ProgramItemGroupVo> programItemGroups = new ObservableCollection<ProgramItemGroupVo>();

        //处理进度条
        private DispatcherTimer timer = new DispatcherTimer();

        //处理切换模式淡入，淡出
        private DispatcherTimer switchInTimer = new DispatcherTimer();
        private DispatcherTimer switchOutTimer = new DispatcherTimer();
        private DispatcherTimer switchOutEndTimer = new DispatcherTimer();
        private DispatcherTimer switchOutPauseTimer = new DispatcherTimer();
        private DispatcherTimer switchOutStopTimer = new DispatcherTimer();
        private DispatcherTimer _playTimer = new DispatcherTimer();
        public DataTable SwitchModeTabe { get; set; }

        public DataTable CycleModeTabe { get; set; }

        /// <summary>
        /// 右键编辑
        /// </summary>
        public DelegateCommand UpdateProgramNameCommand { get; set; }

        public DelegateCommand<Object> UpdateSwitchModeCommand { get; set; }

        public DelegateCommand<Object> ChangeSelectedItemCommand { get; set; }

        public DelegateCommand PlaySettingCommand { get; set; }

        public DelegateCommand AddMusicCommand { get; set; }

        public DelegateCommand AddBlankCommand { get; set; }

        public DelegateCommand DeleteCommand { get; set; }

        public DelegateCommand<Object> PlayMusicCommond { get; set; }

        public DelegateCommand<Object> MediaEndedCommand { get; set; }

        public DelegateCommand<Object> NextCommond { get; set; }

        public DelegateCommand<Object> StopCommond { get; set; }

        public DelegateCommand<Object> LastCommond { get; set; }

        public DelegateCommand ReplaceCommand { get; set; }

        public DelegateCommand<Object> DoubleClickCommond { get; set; }

        public DelegateCommand<object> SpaceKeyCommand { get; set; }

        private ProgramVo program;

        private ListView listView;

        private ObservableCollection<ProgramItemVo> programItems = new ObservableCollection<ProgramItemVo>();


        /// <summary>
        /// 双击开始节目
        /// </summary>
        public DelegateCommand MouseDoubleClickCommond { get; set; }

        public DelegateCommand<object> SelectionChangedCommand { get; set; }
        public ProgramListViewModel(IEventAggregator eventAggregator, IDialogService dialogService, IContainerExtension containerExtension)
        {
            _eventAggregator = eventAggregator;
            ProgramVos = new ObservableCollection<ProgramVo>();

            _eventAggregator.GetEvent<ProgramEvent>().Subscribe(Received);
            _eventAggregator.GetEvent<ProgramItemEvent>().Subscribe(ReceivedList);
            _eventAggregator.GetEvent<SaveProgramEvent>().Subscribe(SaveProgram);
            //用于屏幕监控推送事件
            _eventAggregator.GetEvent<GetMonitorEvent>().Subscribe(GetMonitor);
            //获取打开的屏幕
            _eventAggregator.GetEvent<OpenScreenEvent>().Subscribe(GetOpenScreen);
            //刷新列表
            _eventAggregator.GetEvent<RefreshProgramListEvent>().Subscribe(RefreshList);

            UpdateProgramNameCommand = new DelegateCommand(updateProgramName);
            UpdateSwitchModeCommand = new DelegateCommand<Object>(updateSwitchMode);
            ChangeSelectedItemCommand = new DelegateCommand<Object>(changeSelectedItemCommand);
            PlaySettingCommand = new DelegateCommand(playSettingCommand);

            AddMusicCommand = new DelegateCommand(addMusic);
            AddBlankCommand = new DelegateCommand(addBlank);
            DeleteCommand = new DelegateCommand(deleteProgram);
            //播放音乐
            PlayMusicCommond = new DelegateCommand<Object>(playMusic);
            //曲目结束后执行
            MediaEndedCommand = new DelegateCommand<object>(mediaEnded);
            //下一曲
            NextCommond = new DelegateCommand<object>(nextCommand);
            //暂停
            StopCommond = new DelegateCommand<object>(stopCommond);
            //上一曲
            LastCommond = new DelegateCommand<object>(lastCommond);
            //替换节目
            ReplaceCommand = new DelegateCommand(replaceCommond);
            //双击播放
            DoubleClickCommond = new DelegateCommand<Object>(doubleClick);

            SpaceKeyCommand = new DelegateCommand<object>(playMusic);

            SelectionChangedCommand = new DelegateCommand<object>(selectionChanged);
            this.dialogService = dialogService;
            _containerExtension = containerExtension;

            SwitchModeTabe = new DataTable();
            SwitchModeTabe.Columns.Add("状态值");
            SwitchModeTabe.Columns.Add("状态显示");
            SwitchModeTabe.Rows.Add("1", "淡入");
            SwitchModeTabe.Rows.Add("2", "淡出");
            SwitchModeTabe.Rows.Add("3", "淡入淡出");
            SwitchModeTabe.Rows.Add("4", "无");

            CycleModeTabe = new DataTable();
            CycleModeTabe.Columns.Add("状态值");
            CycleModeTabe.Columns.Add("状态显示");
            CycleModeTabe.Rows.Add("1", "停止");
            CycleModeTabe.Rows.Add("2", "单曲循环");
            CycleModeTabe.Rows.Add("3", "下一曲");
            CycleModeTabe.Rows.Add("4", "A循环");
            CycleModeTabe.Rows.Add("5", "B循环");
            timer.Interval = TimeSpan.FromMilliseconds(5);
            _playTimer.Interval = TimeSpan.FromMilliseconds(5);
            switchInTimer.Interval = TimeSpan.FromMilliseconds(20);
            switchOutTimer.Interval = TimeSpan.FromMilliseconds(20);
            switchOutEndTimer.Interval = TimeSpan.FromMilliseconds(20);
            switchOutPauseTimer.Interval = TimeSpan.FromMilliseconds(20);
            switchOutStopTimer.Interval = TimeSpan.FromMilliseconds(20);
            timer.Tick += Timer_Tick;
            switchInTimer.Tick += SwitchInTimer_Tick;
            switchOutTimer.Tick += SwitchOutTimer_Tick;
            switchOutEndTimer.Tick += SwitchOutEndTimer_Tick;
            switchOutPauseTimer.Tick += SwitchOutPauseTimer_Tick;
            switchOutStopTimer.Tick += SwitchOutStopTimer_Tick;
            _playTimer.Tick += PlayTimerOnTick;
            // 设置定时器回调方法


        }

        private void RefreshList(string obj)
        {
            if (!string.IsNullOrEmpty(obj))
            {
                ObservableCollection<ProgramItemVo> tempList = new ObservableCollection<ProgramItemVo>();
                ObservableCollection<ProgramItemVo> initTempList1 = JsonConvert.DeserializeObject<ObservableCollection<ProgramItemVo>>(obj);
                foreach (ProgramItemVo programItemVo1 in ProgramItems)
                {
                    foreach (ProgramItemVo programItemVo2 in initTempList1)
                    {
                        if (programItemVo2.Id == programItemVo1.Id)
                        {
                            programItemVo1.Name = programItemVo2.Name;
                            programItemVo1.Volume = programItemVo2.Volume;
                            programItemVo1.FilePath = programItemVo2.FilePath;
                            programItemVo1.Type = programItemVo2.Type;
                            programItemVo1.StartWith = programItemVo2.StartWith;
                            programItemVo1.SwitchTime = programItemVo2.SwitchTime;
                            programItemVo1.DoubleMode = programItemVo2.DoubleMode;
                            programItemVo1.SwitchMode = programItemVo2.SwitchMode;
                            programItemVo1.CycleMode = programItemVo2.CycleMode;
                            programItemVo1.EndWith = programItemVo2.EndWith;
                            programItemVo1.SwitchOutTime = programItemVo2.SwitchOutTime;
                            programItemVo1.SourceList = programItemVo2.SourceList;
                            initTempList.Remove(programItemVo2);
                            break;
                        }
                    }




                    tempList.Add(programItemVo1);
                }
                ProgramItems.Clear();
                foreach (ProgramItemVo programItemVo in tempList)
                {
                    ProgramItems.Add(programItemVo);
                }

            }
        }

        private void GetOpenScreen(List<string> obj)
        {
            openScreenIds = obj;
        }

        private void GetMonitor(List<MonitorVo> obj)
        {
            if (null != obj && obj.Count > 0)
            {
                monitorVos = obj;
            }
        }

        private void SaveProgram()
        {
            SaveSourceListVo saveSourceListVo = new SaveSourceListVo();
            saveSourceListVo.Program = program;
            saveSourceListVo.ProgramItems = ProgramItems;
            _eventAggregator.GetEvent<SaveSourceListEvent>().Publish(saveSourceListVo);
        }

        private void PlayTimerOnTick(object sender, EventArgs e)
        {
            if (music.Position.TotalSeconds >= EndWith)
            {
                music.Stop();
                _playTimer.Stop();
                flag = false;
                mediaEnded(music);
            }
        }

        ObservableCollection<ProgramItemVo> realItems = new ObservableCollection<ProgramItemVo>();
        private void selectionChanged(object obj)
        {
            listView = obj as ListView;
            realItems = (ObservableCollection<ProgramItemVo>)listView.ItemsSource;

        }

        private void SwitchOutStopTimer_Tick(object sender, EventArgs e)
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                //你的代码
                double j = Volume / (switchOutTime * 1000 / 30);
                endVolume -= j;
                if (null != music)
                {
                    music.Volume = endVolume;
                }
                if (endVolume <= 0)
                {

                    switchOutStopTimer.Stop();
                    timer.Stop();
                    music.Stop();
                    _playTimer.Stop();
                    StartWith = 0;
                    music.Position = TimeSpan.FromSeconds(0);
                    CurrentTimeStr = "00:00:00";
                    isPause = false;
                    flag = false;
                    PlayText = "播放";

                    IsEnabled = true;
                    _eventAggregator.GetEvent<PlayStatusEvent>().Publish("-1");
                }
            });
        }

        private void SwitchOutPauseTimer_Tick(object sender, EventArgs e)
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                //你的代码
                double j = Volume / (switchOutTime * 1000 / 30);
                endVolume -= j;
                if (null != music)
                {
                    music.Volume = endVolume;
                }
                if (endVolume <= 0)
                {
                    timer.Stop();
                    music.Pause();
                    switchOutPauseTimer.Stop();
                    isPause = true;
                    PlayText = "播放";
                    IsPauseEnabled = true;
                    flag = false;
                    _eventAggregator.GetEvent<PlayStatusEvent>().Publish("0");
                }
            });
        }

        private void SwitchOutEndTimer_Tick(object sender, EventArgs e)
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                //你的代码
                double j = Volume / (switchOutTime * 1000 / 20);
                endVolume -= j;
                if (null != music)
                {
                    music.Volume = endVolume;
                }
                if (endVolume <= 0)
                {
                    //music.Stop();
                    //timer.Stop();
                    //_playTimer.Stop();
                    switchOutEndTimer.Stop();
                    mediaEnded(music);
                    IsPauseEnabled = true;
                    flag = false;
                }
            });
        }

        private double endVolume;
        private void SwitchOutTimer_Tick(object sender, EventArgs e)
        {

            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                //你的代码
                double j = Volume / (switchOutTime * 1000 / 30);
                endVolume -= j;
                if (null != music)
                {
                    music.Volume = endVolume;
                }
                if (endVolume <= 0)
                {
                    switchOutTimer.Stop();
                    music.Stop();
                    timer.Stop();
                    //_playTimer.Stop();
                    CurrentTimeStr = "00:00:00";
                    StartWith = 0;
                    IsPauseEnabled = true;
                    flag = false;
                    isPause = false;
                    PlayText = "播放";
                    playMusic(music);
                }
            });


        }

        private double initVolume = 0;
        private void SwitchInTimer_Tick(object sender, EventArgs e)
        {

            App.Current.Dispatcher.Invoke((Action)delegate ()
            {

                double i = Volume / (switchTime * 1000 / 30);
                initVolume += i;
                if (initVolume >= Volume)
                {
                    music.Volume = Volume;
                    switchInTimer.Stop();
                    initVolume = 0;
                    flag = false;
                }
                else
                {
                    music.Volume = initVolume;
                }
            });


        }

        bool playFlag = false;

        private void doubleClick(Object obj)
        {
            System.Windows.Input.MouseEventArgs e = (System.Windows.Input.MouseEventArgs)obj;
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                switchInTimer.Stop();
                switchOutTimer.Stop();
                currentProgram = SelectedItem;
                if (String.IsNullOrEmpty(currentMusicId) || !currentMusicId.Equals(SelectedItem.Id))
                {


                    if (!String.IsNullOrEmpty(currentMusicId) && !currentMusicId.Equals(SelectedItem.Id) && !String.IsNullOrEmpty(switchMode) && ("2".Equals(switchMode) || "3".Equals(switchMode)) && switchOutTime > 0
                       && playText.Equals("暂停"))
                    {
                        endVolume = music.Volume;
                        switchOutTimer.Start();
                        //防止淡出快到结尾开启两个定时任务效果
                        flag = true;
                    }
                    else
                    {
                        isPause = false;
                        PlayText = "播放";
                        playMusic(music);
                    }

                    return;
                }
                if (!String.IsNullOrEmpty(SelectedItem.DoubleMode) && SelectedItem.DoubleMode.Equals("2") && currentMusicId.Equals(SelectedItem.Id))
                {

                    //停止
                    if (PlayText.Equals("暂停"))
                    {


                        stopCommond(music);

                    }
                    else
                    {

                        playMusic(music);

                    }
                    return;
                }
                //暂停
                if ((String.IsNullOrEmpty(SelectedItem.DoubleMode) || SelectedItem.DoubleMode.Equals("1")) && currentMusicId.Equals(SelectedItem.Id))
                {
                    playMusic(music);
                    return;
                }
            }
        }

        private void replaceCommond()
        {

            if (PlayFlag)
            {
                MessageBox.Show("有节目播放中，不能修改！");
                return;
            }
            if (null == program || null == SelectedItem)
            {
                System.Windows.MessageBox.Show("请先选择节目！");
                return;
            }
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "选择音频";
            openFileDialog.Filter = "音频文件|*.mp3; *.wav";
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                fileFullPath = program.FilePath + "\\" + program.Name + ".info"; // 指定要创建的文件路径及名称
                try
                {
                    if (!File.Exists(fileFullPath))
                    {
                        MessageBox.Show("文件不存在！");
                        return;
                    }
                    long timeStamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
                    string name = Path.GetFileNameWithoutExtension(filePath);
                    ProgramItemVo programItemVo = new ProgramItemVo(0, name, filePath, "1", "4", "100", "0", "1", timeStamp + "");
                    string content = WriteFileUtil.readFile(fileFullPath);
                    if (!String.IsNullOrEmpty(content))
                    {
                        JObject programJson = JsonConvert.DeserializeObject<JObject>(content);
                        ObservableCollection<ProgramItemVo> programItems = new ObservableCollection<ProgramItemVo>();
                        if (programJson.ContainsKey("programItems"))
                        {
                            programItems = JsonConvert.DeserializeObject<ObservableCollection<ProgramItemVo>>((String)programJson.GetValue("programItems"));
                        }

                        foreach (ProgramItemVo p in programItems)
                        {
                            if (p.Id.Equals(SelectedItem.Id))
                            {
                                p.FilePath = filePath;
                                p.Name = name;
                                p.Type = "1";
                                p.CycleMode = string.IsNullOrEmpty(SelectedItem.CycleMode) ? "0" : SelectedItem.CycleMode;
                                p.SwitchMode = string.IsNullOrEmpty(SelectedItem.SwitchMode) ? "4" : SelectedItem.SwitchMode;
                                p.Volume = string.IsNullOrEmpty(SelectedItem.Volume) ? "100" : SelectedItem.Volume;
                                p.StartWith = string.IsNullOrEmpty(SelectedItem.StartWith) ? "0" : SelectedItem.StartWith;
                                programItemVo = p;
                                break;
                            }
                        }

                        if (programJson.ContainsKey("programItems"))
                        {
                            programJson["programItems"] = JsonConvert.SerializeObject(programItems);
                        }
                        else
                        {
                            programJson.Add("programItems", JsonConvert.SerializeObject(programItems));
                        }
                        WriteFileUtil.writeFile(fileFullPath, JsonConvert.SerializeObject(programJson), "2");

                    }

                    _eventAggregator.GetEvent<ProgramItemEvent>().Publish(programItemVo);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"创建节目失败：{ex.Message}");
                    return;
                }

            }
        }

        private void lastCommond(object obj)
        {
            ObservableCollection<ProgramItemVo> cycleList = new ObservableCollection<ProgramItemVo>();
            var groupList = realItems.GroupBy(s => s.CycleMode);

            foreach (var group1 in groupList)
            {
                if (group1.Key.Equals("4") || group1.Key.Equals("5"))
                {
                    cycleList.Add(group1.First<ProgramItemVo>());
                }
                else
                {
                    cycleList.AddRange(group1.ToList<ProgramItemVo>());
                }
            }
            for (int i = 0; i < cycleList.Count; i++)
            {
                if (cycleList[i].Id.Equals(currentProgram.Id))
                {
                    currentIndex = i;
                    break;
                }
                if (!cycleList[i].Id.Equals(currentProgram.Id) && cycleList[i].CycleMode.Equals(cycleMode) && (cycleMode.Equals("4") || cycleMode.Equals("5")))
                {
                    currentIndex = i;
                    break;
                }
            }
            currentIndex--;

            if (currentIndex < 0)
            {
                currentIndex = cycleList.Count - 1;
            }

            currentProgram = cycleList[currentIndex];
            if (!String.IsNullOrEmpty(switchMode) && ("2".Equals(switchMode) || "3".Equals(switchMode)) && switchOutTime > 0 && playText.Equals("暂停"))
            {
                endVolume = music.Volume;
                switchOutTimer.Start();
                //防止淡出快到结尾开启两个定时任务效果
                flag = true;
            }
            else
            {


                isPause = false;
                PlayText = "播放";
                playMusic(obj);
            }

        }

        private void stopCommond(object obj)
        {
            IsEnabled = false;
            if (!String.IsNullOrEmpty(switchMode) && ("2".Equals(switchMode) || "3".Equals(switchMode)) && switchOutTime > 0 &&
                playText.Equals("暂停"))
            {
                endVolume = music.Volume;
                switchOutStopTimer.Start();
                //防止淡出快到结尾开启两个定时任务效果
                flag = true;

            }
            else
            {
                music = obj as MediaElement;
                music.Stop();
                timer.Stop();
                _playTimer.Stop();
                StartWith = 0;
                music.Position = TimeSpan.FromSeconds(0);
                CurrentTimeStr = "00:00:00";
                isPause = false;
                PlayText = "播放";
                /*
                if (null != sourceWindowList && sourceWindowList.Count > 0)
                {
                    foreach (var win in sourceWindowList)
                    {
                        win.Close();
                    }
                    sourceWindowList.Clear();
                }*/
                IsEnabled = true;
                _eventAggregator.GetEvent<PlayStatusEvent>().Publish("-1");
            }
            PlayFlag = false;
            IsDisplay = true;
            _eventAggregator.GetEvent<PlaySettingFlagEvent>().Publish(PlayFlag);
            // _eventAggregator.GetEvent<PlayStatusEvent>().Publish("0");
        }

        private void nextCommand(object obj)
        {
            ObservableCollection<ProgramItemVo> cycleList = new ObservableCollection<ProgramItemVo>();
            var groupList = realItems.GroupBy(s => s.CycleMode);

            foreach (var group1 in groupList)
            {
                if (group1.Key.Equals("4") || group1.Key.Equals("5"))
                {
                    cycleList.Add(group1.First<ProgramItemVo>());
                }
                else
                {
                    cycleList.AddRange(group1.ToList<ProgramItemVo>());
                }
            }
            for (int i = 0; i < cycleList.Count; i++)
            {
                if (cycleList[i].Id.Equals(currentProgram.Id))
                {
                    currentIndex = i;
                    break;
                }
                if (!cycleList[i].Id.Equals(currentProgram.Id) && cycleList[i].CycleMode.Equals(cycleMode) && (cycleMode.Equals("4") || cycleMode.Equals("5")))
                {
                    currentIndex = i;
                    break;
                }
            }
            currentIndex++;
            if (currentIndex >= cycleList.Count)
            {
                currentIndex = 0;
            }

            currentProgram = cycleList[currentIndex];
            if (!String.IsNullOrEmpty(switchMode) && ("2".Equals(switchMode) || "3".Equals(switchMode)) && switchOutTime > 0 && playText.Equals("暂停"))
            {
                endVolume = music.Volume;
                switchOutTimer.Start();
                //防止淡出快到结尾开启两个定时任务效果
                flag = true;
            }
            else
            {

                isPause = false;
                PlayText = "播放";
                playMusic(obj);
            }

        }

        private void mediaEnded(object obj)
        {
            timer.Stop();
            switchOutTimer.Stop();
            switchInTimer.Stop();
            switchOutPauseTimer.Stop();
            switchOutStopTimer.Stop();
            switchOutEndTimer.Stop();
            _playTimer.Stop();
            _eventAggregator.GetEvent<PlayStatusEvent>().Publish("-2");
            flag = false;
            ProgramItemGroupVo programItemGroup = programItemGroups[cycleIndex];
            switch (cycleMode)
            {
                case "1":
                    PlayText = "播放";
                    PlayFlag = false;
                    IsDisplay = true;
                    _eventAggregator.GetEvent<PlaySettingFlagEvent>().Publish(PlayFlag);
                    break;
                case "2":
                    //单曲循环
                    cycleMode = programItemGroup.CycleModel;
                    programItemGroup.CurrentProgram = currentProgram;
                    playProgram(obj, programItemGroup);
                    if ("1".Equals(currentProgram.Type))
                    {
                        timer.Start();
                    }
                    break;
                case "0":
                    nextIndex++;
                    if (currentList.Count <= nextIndex)
                    {
                        nextIndex = 0;
                    }
                    currentProgram = currentList[nextIndex];
                    cycleMode = programItemGroup.CycleModel;
                    programItemGroup.CurrentProgram = currentProgram;
                    playProgram(obj, programItemGroup);
                    if ("1".Equals(currentProgram.Type))
                    {
                        timer.Start();
                    }
                    _eventAggregator.GetEvent<SelectedProgramItemEvent>().Publish(currentProgram);
                    break;
                case "3":
                    nextIndex++;
                    if (currentList.Count <= nextIndex)
                    {
                        nextIndex = 0;
                        currentProgram = currentList[nextIndex];
                        return;
                    }
                    currentProgram = currentList[currentIndex];
                    cycleMode = programItemGroup.CycleModel;
                    programItemGroup.CurrentProgram = currentProgram;
                    playProgram(obj, programItemGroup);
                    if ("1".Equals(currentProgram.Type))
                    {
                        timer.Start();
                    }
                    _eventAggregator.GetEvent<SelectedProgramItemEvent>().Publish(currentProgram);
                    break;
                case "4":
                    nextIndex++;
                    if (currentList.Count <= nextIndex)
                    {
                        nextIndex = 0;
                    }
                    currentProgram = currentList[nextIndex];
                    cycleMode = programItemGroup.CycleModel;
                    programItemGroup.CurrentProgram = currentProgram;
                    playProgram(obj, programItemGroup);
                    if ("1".Equals(currentProgram.Type))
                    {
                        timer.Start();
                    }
                    _eventAggregator.GetEvent<SelectedProgramItemEvent>().Publish(currentProgram);
                    break;
                case "5":
                    nextIndex++;
                    if (currentList.Count <= nextIndex)
                    {
                        nextIndex = 0;
                    }
                    currentProgram = currentList[nextIndex];
                    cycleMode = programItemGroup.CycleModel;
                    programItemGroup.CurrentProgram = currentProgram;
                    playProgram(obj, programItemGroup);
                    if ("1".Equals(currentProgram.Type))
                    {
                        timer.Start();
                    }
                    _eventAggregator.GetEvent<SelectedProgramItemEvent>().Publish(currentProgram);
                    break;
            }
        }

        private bool flag = false;
        private void Timer_Tick(object sender, EventArgs e)
        {

            double value = music.Position.TotalMilliseconds / 1000;
            int h = (int)value / 60 / 60 % 24;
            int m = (int)value / 60 % 60;
            int s = (int)value % 60;
            string hh = h.ToString();
            hh = h < 10 ? '0' + hh : hh;
            string mm = m.ToString();
            mm = m < 10 ? '0' + mm : mm;
            string ss = s.ToString();
            ss = s < 10 ? '0' + ss : ss;
            CurrentTimeStr = hh + ":" + mm + ":" + ss;
            TestVolume = music.Volume;
            if (!String.IsNullOrEmpty(switchMode) && ("2".Equals(switchMode) || "3".Equals(switchMode)) && playText.Equals("暂停"))
            {
                if ((int)music.Position.TotalSeconds >= (EndWith - switchOutTime - 1) && !flag)
                {
                    flag = true;
                    endVolume = music.Volume;
                    switchOutEndTimer.Start();
                }
            }

        }

        private int nextIndex = 0;
        /// <summary>
        /// 播放音乐
        /// </summary>
        private void playMusic(object obj)
        {
            PlayFlag = true;
            IsDisplay = false;
            _eventAggregator.GetEvent<PlaySettingFlagEvent>().Publish(PlayFlag);
            flag = false;
            //处理播放暂停
            if (PlayText.Equals("播放"))
            {

                PlayText = "暂停";
                IsPauseEnabled = true;
                _eventAggregator.GetEvent<PlayStatusEvent>().Publish("1");
            }
            else
            {
                IsPauseEnabled = false;
                if (!String.IsNullOrEmpty(switchMode) && ("2".Equals(switchMode) || "3".Equals(switchMode)) && switchOutTime > 0)
                {
                    endVolume = music.Volume;
                    switchOutPauseTimer.Start();
                    //防止淡出快到结尾开启两个定时任务效果
                    flag = true;


                }
                else
                {
                    music.Pause();
                    timer.Stop();
                    isPause = true;
                    PlayText = "播放";
                    IsPauseEnabled = true;
                    _eventAggregator.GetEvent<PlayStatusEvent>().Publish("0");
                }
                return;
            }
            if (null == currentProgram)
            {
                currentProgram = SelectedItem;
            }


            //先按循环模式分组，再判断当前选择的模式进行播放
            programItemGroups = getProgramItemGroupByCycleModel();
            ProgramItemGroupVo programItemGroupVo1 = new ProgramItemGroupVo();
            if (null != programItemGroups && programItemGroups.Count > 0)
            {
                foreach (ProgramItemGroupVo programItemGroupVo in programItemGroups)
                {
                    if (programItemGroupVo.CycleModel.Equals(currentProgram.CycleMode))
                    {
                        currentList = programItemGroupVo.ProgramItemVos;
                        programItemGroupVo1 = programItemGroupVo;
                        programItemGroupVo1.CurrentProgram = currentProgram;
                        break;
                    }
                }
            }
            if (null != currentList && currentList.Count > 0)
            {
                //保存点击的节目下标索引,用于循环下一个节目
                for (int j = 0; j < currentList.Count; j++)
                {
                    if (currentList[j].Id.Equals(currentProgram.Id))
                    {
                        nextIndex = j;
                        break;
                    }
                }
            }
            //保存点击的节目下标索引,用于下一个节目


            ObservableCollection<ProgramItemVo> cycleList = new ObservableCollection<ProgramItemVo>();
            var groupList = realItems.GroupBy(s => s.CycleMode);

            foreach (var group1 in groupList)
            {
                if (group1.Key.Equals("4") || group1.Key.Equals("5"))
                {
                    cycleList.Add(group1.First<ProgramItemVo>());
                }
                else
                {
                    cycleList.AddRange(group1.ToList<ProgramItemVo>());
                }
            }
            for (int i = 0; i < cycleList.Count; i++)
            {
                if (cycleList[i].Id.Equals(currentProgram.Id) || cycleList[i].CycleMode.Equals("4") || cycleList[i].CycleMode.Equals("5"))
                {
                    currentIndex = i;
                    break;
                }
            }
            playProgram(obj, programItemGroupVo1);
        }

        private void deleteProgram()
        {

            if (PlayFlag)
            {
                MessageBox.Show("有节目播放中，不能修改！");
                return;
            }
            if (null != currentProgram && SelectedItem.Id.Equals(currentProgram.Id))
            {
                if (null != music)
                {
                    music.Stop();
                    music.Source = null;

                }
                playText = "播放";
                currentProgram = null;
                CurrentMusic = "";
                MaxValue = 0;
            }
            //删除节目
            if (null != SelectedItem)
            {
                if (null != program)
                {
                    fileFullPath = program.FilePath + "\\" + program.Name + ".info"; // 指定要创建的文件路径及名称
                    try
                    {
                        if (!File.Exists(fileFullPath))
                        {
                            MessageBox.Show("文件不存在！");
                            return;
                        }
                        string content = WriteFileUtil.readFile(fileFullPath);
                        if (!String.IsNullOrEmpty(content))
                        {
                            JObject programJson = JsonConvert.DeserializeObject<JObject>(content);
                            ObservableCollection<ProgramItemVo> programItemList = new ObservableCollection<ProgramItemVo>();
                            if (programJson.ContainsKey("programItems"))
                            {
                                programItemList = JsonConvert.DeserializeObject<ObservableCollection<ProgramItemVo>>((String)programJson.GetValue("programItems"));
                                foreach (ProgramItemVo programItemVo in programItemList)
                                {
                                    if (programItemVo.Id.Equals(SelectedItem.Id))
                                    {
                                        programItemList.Remove(programItemVo);
                                        break;
                                    }
                                }
                                foreach (ProgramItemVo programItemVo1 in ProgramItems)
                                {
                                    if (programItemVo1.Id.Equals(SelectedItem.Id))
                                    {
                                        ProgramItems.Remove(programItemVo1);
                                        break;
                                    }
                                }
                            }
                            if (programJson.ContainsKey("programItems"))
                            {
                                programJson["programItems"] = JsonConvert.SerializeObject(programItems);
                            }
                            else
                            {
                                programJson.Add("programItems", JsonConvert.SerializeObject(programItems));
                            }
                            WriteFileUtil.writeFile(fileFullPath, JsonConvert.SerializeObject(programJson), "2");
                        }



                    }
                    catch (Exception ex)
                    {

                    }

                }
            }
        }

        private void addBlank()
        {
            if (null == program)
            {
                MessageBox.Show("请先选择节目！");
                return;
            }
            //保存节目
            if (null != program)
            {
                fileFullPath = program.FilePath + "\\" + program.Name + ".info"; // 指定要创建的文件路径及名称
                try
                {
                    if (!File.Exists(fileFullPath))
                    {
                        MessageBox.Show("文件不存在！");
                        return;
                    }
                    long timeStamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
                    ProgramItemVo programItemVo = new ProgramItemVo(0, "空白节目", "", "2", "", "", "", "1", timeStamp + "");
                    string content = WriteFileUtil.readFile(fileFullPath);
                    if (!String.IsNullOrEmpty(content))
                    {
                        ObservableCollection<ProgramItemVo> programItems1 = new ObservableCollection<ProgramItemVo>();
                        JObject programJson = JsonConvert.DeserializeObject<JObject>(content);
                        if (programJson.ContainsKey("programItems"))
                        {
                            programItems1 = JsonConvert.DeserializeObject<ObservableCollection<ProgramItemVo>>((String)programJson.GetValue("programItems"));
                        }
                        programItemVo.No = programItems1.Count + 1;
                        programItems1.Add(programItemVo);
                        ProgramItems.Add(programItemVo);
                        if (programJson.ContainsKey("programItems"))
                        {
                            programJson["programItems"] = JsonConvert.SerializeObject(programItems1);
                        }
                        else
                        {
                            programJson.Add("programItems", JsonConvert.SerializeObject(programItems1));
                        }
                        WriteFileUtil.writeFile(fileFullPath, JsonConvert.SerializeObject(programJson), "2");
                    }
                }
                catch (Exception ex)
                {

                }
            }
        }

        private void ReceivedList(ProgramItemVo obj)
        {

            if (null == obj)
            {
                return;
            }
            /*
            bool addFlag = true;
            ObservableCollection<ProgramItemVo> tempList = new ObservableCollection<ProgramItemVo>();
            foreach (ProgramItemVo programItemVo in ProgramItems)
            {
                if (obj.Id.Equals(programItemVo.Id))
                {
                    addFlag = false;
                    break;
                }

            }*/
            //initList();
            if (null != SelectedItem)
            {
                if (obj.Id.Equals(SelectedItem.Id))
                {
                    SelectedItem.Name = obj.Name;
                    SelectedItem.Volume = obj.Volume;
                    SelectedItem.FilePath = obj.FilePath;
                    SelectedItem.Type = obj.Type;
                    SelectedItem.StartWith = obj.StartWith;
                    SelectedItem.DoubleMode = obj.DoubleMode;
                    SelectedItem.SwitchTime = obj.SwitchTime;
                    SelectedItem.SwitchMode = obj.SwitchMode;
                    SelectedItem.CycleMode = obj.CycleMode;
                    SelectedItem.EndWith = obj.EndWith;
                    SelectedItem.SwitchOutTime = obj.SwitchOutTime;
                    SelectedItem.SourceList = obj.SourceList;




                    //cycleMode = obj.CycleMode;
                    //switchMode = obj.SwitchMode;
                }
            }
            if (null != currentProgram)
            {
                if (obj.Id.Equals(currentProgram.Id))
                {
                    string type = currentProgram.Type;
                    string filePath = currentProgram.FilePath;
                    currentProgram.Name = obj.Name;
                    currentProgram.FilePath = obj.FilePath;
                    currentProgram.Type = obj.Type;
                    currentProgram.Volume = obj.Volume;
                    currentProgram.StartWith = obj.StartWith;
                    currentProgram.DoubleMode = obj.DoubleMode;
                    currentProgram.SwitchTime = obj.SwitchTime;
                    currentProgram.SwitchMode = obj.SwitchMode;
                    currentProgram.CycleMode = obj.CycleMode;
                    currentProgram.EndWith = obj.EndWith;
                    currentProgram.SwitchOutTime = obj.SwitchOutTime;
                    currentProgram.SourceList = obj.SourceList;
                    cycleMode = obj.CycleMode;
                    switchMode = obj.SwitchMode;
                    if (!string.IsNullOrEmpty(obj.SwitchTime))
                    {
                        switchTime = Convert.ToInt32(obj.SwitchTime);
                    }
                    else
                    {
                        switchTime = 5;
                    }
                    if (!string.IsNullOrEmpty(obj.SwitchOutTime))
                    {
                        switchOutTime = Convert.ToInt32(obj.SwitchOutTime);
                    }
                    else
                    {
                        switchOutTime = 5;
                    }
                    if (null != music && (!type.Equals(obj.Type) || !filePath.Equals(obj.FilePath)))
                    {
                        playText = "播放";
                        isPause = false;
                        playMusic(music);
                    }
                }
            }
            //选中
            /*
            listView.Dispatcher.Invoke(() =>
            {
                if (null != realItems && realItems.Count > 0)
                {
                    for (int i = 0; i < realItems.Count; i++)
                    {
                        if (realItems[i].Id.Equals(currentProgram.Id))
                        {
                            //SelectedIndex = i;
                            //ListViewItem item = (ListViewItem)listView.ItemContainerGenerator.ContainerFromIndex(i);
                            //item.IsFocused = true;
                            //item.Focus();
                            //item.IsSelected = true;
                            // 现在item就是您通过下标获取的ListViewItem
                            //listView.SelectedItem = item;
                            //listView.SelectedIndex = i;
                            //listView.Focus();
                            break;
                        }
                    }
                }
            });*/


        }

        private void addMusic()
        {
            if (null == program)
            {
                MessageBox.Show("请先选择节目！");
                return;
            }
            //IDialogParameters parameters = new DialogParameters();
            //parameters.Add("program", program);
            //dialogService.ShowDialog("addMusic", parameters, callback);

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "选择音频";
            openFileDialog.Filter = "音频文件|*.mp3; *.wav";
            openFileDialog.Multiselect = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string fileFullPath = program.FilePath + "\\" + program.Name + ".info"; // 指定要创建的文件路径及名称
                try
                {
                    if (!File.Exists(fileFullPath))
                    {
                        MessageBox.Show("文件不存在！");
                        return;
                    }
                    string content = WriteFileUtil.readFile(fileFullPath);
                    if (!String.IsNullOrEmpty(content))
                    {

                        JObject programJson = JsonConvert.DeserializeObject<JObject>(content);
                        ObservableCollection<ProgramItemVo> programItems1 = new ObservableCollection<ProgramItemVo>();
                        if (programJson.ContainsKey("programItems"))
                        {
                            programItems1 = JsonConvert.DeserializeObject<ObservableCollection<ProgramItemVo>>((String)programJson.GetValue("programItems"));
                        }
                        int i = programItems1.Count + 1;
                        foreach (string item in openFileDialog.FileNames)
                        {
                            Thread.Sleep(2);
                            long timeStamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
                            string name = Path.GetFileNameWithoutExtension(item);
                            ProgramItemVo programItemVo = new ProgramItemVo(0, name, item, "1", "4", "100", "0", "1", timeStamp + "");
                            programItemVo.No = i++;
                            ProgramItems.Add(programItemVo);
                            programItems1.Add(programItemVo);
                        }
                        if (programJson.ContainsKey("programItems"))
                        {
                            programJson["programItems"] = JsonConvert.SerializeObject(programItems1);
                        }
                        else
                        {
                            programJson.Add("programItems", JsonConvert.SerializeObject(programItems1));
                        }
                        WriteFileUtil.writeFile(fileFullPath, JsonConvert.SerializeObject(programJson), "2");
                        //_eventAggregator.GetEvent<ProgramEvent>().Publish(program);
                    }

                }
                catch (Exception ex)
                {

                }



            }
        }

        private void playSettingCommand()
        {
            if (PlayFlag)
            {
                MessageBox.Show("有节目播放中，不能修改！");
                return;
            }
            if (null == SelectedItem)
            {
                return;
            }
            if (SelectedItem.Type.Equals("1"))
            {
                IDialogParameters parameters = new DialogParameters();
                parameters.Add("programItem", SelectedItem);
                parameters.Add("program", program);
                dialogService.ShowDialog("playSetting", parameters, callback);
            }
        }

        private void changeSelectedItemCommand(Object obj)
        {



            ListView listView = obj as ListView;
            //SelectedItem = realItems[listView.SelectedIndex];
            SelectedItem = listView.SelectedItem as ProgramItemVo;
            Trace.WriteLine("索引" + listView.SelectedIndex);
            if (null != SelectedItem)
            {

                //SelectedItem = (ProgramItemVo)programItemVo;
                Trace.WriteLine("索引" + SelectedItem.Name);
                //currentProgram = null;
                _eventAggregator.GetEvent<SelectedProgramItemEvent>().Publish(SelectedItem);
                if (null != realItems && realItems.Count > 0)
                {
                    for (int i = 0; i < realItems.Count; i++)
                    {
                        ListViewItem item = (ListViewItem)listView.ItemContainerGenerator.ContainerFromIndex(i);


                        if (null != currentProgram && realItems[i].Id.Equals(currentProgram.Id))
                        {
                            //SelectedIndex = i;

                            //item.IsFocused = true;
                            //item.Focus();
                            //item.IsSelected = true;
                            // 现在item就是您通过下标获取的ListViewItem
                            //listView.SelectedItem = item;
                            item.Background = Brushes.LightBlue;

                        }
                        else
                        {
                            if (realItems[i].Id.Equals(SelectedItem.Id))
                            {
                                item.Background = Brushes.Gray;
                            }
                            else
                            {
                                item.Background = new SolidColorBrush(Color.FromArgb(0x00, 0xFF, 0xFF, 0xFF));
                            }
                        }
                    }
                }

            }

        }

        private void updateSwitchMode(Object obj)
        {
            //if (null != obj as ProgramItemVo) { SelectedItem = (ProgramItemVo)obj; }
            if (null == SelectedItem)
            {
                //SelectedItem = ProgramItems[SelectedIndex];
                return;
            }
            fileFullPath = program.FilePath + "\\" + program.Name + ".info"; // 指定要创建的文件路径及名称
            try
            {
                if (!File.Exists(fileFullPath))
                {
                    MessageBox.Show("节目信息不存在！");
                    return;
                }
                string content = WriteFileUtil.readFile(fileFullPath);
                JObject programJson = JsonConvert.DeserializeObject<JObject>(content);
                ObservableCollection<ProgramItemVo> tempList = JsonConvert.DeserializeObject<ObservableCollection<ProgramItemVo>>((String)programJson.GetValue("programItems"));
                foreach (ProgramItemVo programItemVo in tempList)
                {
                    if (programItemVo.Id.Equals(SelectedItem.Id))
                    {
                        programItemVo.SwitchMode = SelectedItem.SwitchMode;
                        programItemVo.CycleMode = SelectedItem.CycleMode;
                        break;
                    }

                }
                foreach (ProgramItemVo programItemVo1 in ProgramItems)
                {
                    if (programItemVo1.Id.Equals(SelectedItem.Id))
                    {
                        programItemVo1.SwitchMode = SelectedItem.SwitchMode;
                        programItemVo1.CycleMode = SelectedItem.CycleMode;
                        break;
                    }
                }
                if (null != currentProgram && SelectedItem.Id.Equals(currentProgram.Id))
                {
                    switchMode = selectedItem.SwitchMode;
                    cycleMode = selectedItem.CycleMode;
                }
                programJson["programItems"] = JsonConvert.SerializeObject(tempList);
                WriteFileUtil.writeFile(fileFullPath, JsonConvert.SerializeObject(programJson), "2");

            }
            catch (Exception ex)
            {
                MessageBox.Show($"修改节目信息失败：{ex.Message}");
                return;
            }
        }

        private void updateProgramName()
        {
            if (PlayFlag)
            {
                MessageBox.Show("有节目播放中，不能修改！");
                return;
            }
            if (null == SelectedItem)
            {
                return;
            }
            IDialogParameters parameters = new DialogParameters();
            parameters.Add("programItem", SelectedItem);
            parameters.Add("program", program);
            dialogService.ShowDialog("updateProgram", parameters, callback);
        }

        private void callback(IDialogResult result)
        {
            if (result.Result == ButtonResult.OK)
            {
                ProgramItemVo programItemVo = result.Parameters.GetValue<ProgramItemVo>("programItem");
                if (null != programItemVo)
                {
                    ObservableCollection<ProgramItemVo> tempList = new ObservableCollection<ProgramItemVo>();
                    foreach (ProgramItemVo programItemVo1 in ProgramItems)
                    {
                        if (programItemVo1.Id.Equals(programItemVo.Id))
                        {
                            programItemVo1.Name = programItemVo.Name;
                            
                        }
                        tempList.Add(programItemVo1);
                    }
                    ProgramItems.Clear();
                    ProgramItems = tempList; 
                }
            }
        }



        private void Received(ProgramVo obj)
        {
            program = obj;
            ProgramItems.Clear();
            if (null != program)
            {
                fileFullPath = program.FilePath + "\\" + program.Name + ".info"; // 指定要创建的文件路径及名称
                try
                {
                    if (!File.Exists(fileFullPath))
                    {
                        MessageBox.Show("文件不存在！");
                        return;
                    }
                    switchOutTimer.Stop();
                    switchInTimer.Stop();
                    switchOutPauseTimer.Stop();
                    switchOutEndTimer.Stop();
                    switchOutStopTimer.Stop();
                    timer.Stop();
                    if (null != music)
                    {
                        music.Position = new TimeSpan(0, 0, 0);
                        music.Stop();
                    }
                    StartWith = 0;
                    _playTimer.Stop();
                    CurrentMusic = null;
                    currentProgram = null;
                    PlayFlag = false;
                    CurrentTimeStr = "00:00:00";
                    isPause = false;
                    PlayText = "播放";
                    string content = WriteFileUtil.readFile(fileFullPath);
                    if (!String.IsNullOrEmpty(content))
                    {
                        JObject programJson = JsonConvert.DeserializeObject<JObject>(content);
                        if (programJson.ContainsKey("programItems"))
                        {
                            ProgramItems = JsonConvert.DeserializeObject<ObservableCollection<ProgramItemVo>>((String)programJson.GetValue("programItems"));
                            for (int i = 0; i < ProgramItems.Count; i++)
                            {
                                ProgramItems[i].No = i + 1;
                            }
                        }
                    }



                }
                catch (Exception ex)
                {

                }

            }
        }

        private ObservableCollection<ProgramItemGroupVo> getProgramItemGroupByCycleModel()
        {
            ObservableCollection<ProgramItemGroupVo> programItemGroupVos = new ObservableCollection<ProgramItemGroupVo>();
            if (null != ProgramItems && ProgramItems.Count > 0)
            {
                var grouplist = ProgramItems.GroupBy(s => s.CycleMode);
                foreach (var group in grouplist)
                {
                    ProgramItemGroupVo programItemGroupVo = new ProgramItemGroupVo();
                    programItemGroupVo.CycleModel = group.Key;
                    List<ProgramItemVo> list = group.ToList<ProgramItemVo>();
                    ObservableCollection<ProgramItemVo> tempList = new ObservableCollection<ProgramItemVo>();
                    foreach (ProgramItemVo programItemVo in list)
                    {
                        tempList.Add(programItemVo);
                    }
                    programItemGroupVo.ProgramItemVos = tempList;
                    programItemGroupVos.Add(programItemGroupVo);
                }
            }
            return programItemGroupVos;
        }

        private void playProgram(Object obj, ProgramItemGroupVo programItemGroupVo)
        {
            switchInTimer.Stop();
            if (null != realItems && realItems.Count > 0)
            {
                for (int i = 0; i < realItems.Count; i++)
                {
                    ListViewItem item = (ListViewItem)listView.ItemContainerGenerator.ContainerFromIndex(i);


                    if (realItems[i].Id.Equals(currentProgram.Id))
                    {
                        //SelectedIndex = i;

                        //item.IsFocused = true;
                        //item.Focus();
                        //item.IsSelected = true;
                        // 现在item就是您通过下标获取的ListViewItem
                        //listView.SelectedItem = item;
                        item.Background = Brushes.LightBlue;

                    }
                    else
                    {
                        item.Background = new SolidColorBrush(Color.FromArgb(0x00, 0xFF, 0xFF, 0xFF));
                    }
                }
            }

            music = obj as MediaElement;

            switchMode = currentProgram.SwitchMode;
            cycleMode = currentProgram.CycleMode;
            if (!String.IsNullOrEmpty(currentProgram.SwitchTime))
            {
                switchTime = Convert.ToInt16(currentProgram.SwitchTime);
            }
            else
            {
                switchTime = 5;
            }
            if (!string.IsNullOrEmpty(currentProgram.SwitchOutTime))
            {
                switchOutTime = Convert.ToInt32(currentProgram.SwitchOutTime);
            }
            else
            {
                switchOutTime = 5;
            }
            currentMusicId = currentProgram.Id;

            if (isPause)
            {
                //music.Position = TimeSpan.FromSeconds(MaxValue - 2);
                if (!String.IsNullOrEmpty(currentProgram.EndWith))
                {
                    EndWith = Convert.ToDouble(currentProgram.EndWith);
                }
                else
                {
                    EndWith = MaxValue;
                }
                music.Play();
                timer.Start();
                if (!String.IsNullOrEmpty(currentProgram.Volume))
                {

                    Volume = Convert.ToDouble(currentProgram.Volume) / 100;
                }
                else
                {
                    Volume = 1;
                }
                if (!String.IsNullOrEmpty(switchMode) && ("1".Equals(switchMode) || "3".Equals(switchMode)) && switchTime > 0)
                {
                    music.Volume = 0;
                    switchInTimer.Start();

                }
                else
                {
                    music.Volume = Volume;
                }
                _playTimer.Start();
                _eventAggregator.GetEvent<PlayStatusEvent>().Publish("1");
                isPause = false;
                return;
            }
            // _eventAggregator.GetEvent<ClearPlaySourceEvent>().Publish();
            CurrentMusic = currentProgram.Name;
            StartWith = 0;

            if (null != currentProgram && "1".Equals(currentProgram.Type))
            {
                CheckBoxEnable = true;
                VolumeEnable = true;
                if (!String.IsNullOrEmpty(currentProgram.Volume))
                {

                    Volume = Convert.ToDouble(currentProgram.Volume) / 100;
                }
                else
                {
                    Volume = 1;
                }

                int h = 0; int m = 0; int s = 0;
                if (!String.IsNullOrEmpty(currentProgram.StartWith))
                {
                    StartWith = Convert.ToInt32(currentProgram.StartWith);
                    h = Convert.ToInt32(currentProgram.StartWith) / 3600;
                    m = (Convert.ToInt32(currentProgram.StartWith) - (h * 3600)) / 60;
                    s = (Convert.ToInt32(currentProgram.StartWith) - (h * 3600) - (m * 60));
                }
                MaxValue = WriteFileUtil.getMusicTimes(currentProgram.FilePath);

                if (!String.IsNullOrEmpty(currentProgram.EndWith))
                {
                    EndWith = Convert.ToDouble(currentProgram.EndWith);
                }
                else
                {
                    EndWith = MaxValue;
                }
                if (currentProgram.Type.Equals("1"))
                {
                    music.Source = new Uri(currentProgram.FilePath, UriKind.Relative);
                }
                if (!String.IsNullOrEmpty(currentProgram.CycleMode))
                {
                    cycleMode = currentProgram.CycleMode;
                }
                if (!String.IsNullOrEmpty(currentProgram.SwitchTime))
                {
                    switchTime = Convert.ToInt16(currentProgram.SwitchTime);
                }
                else
                {
                    switchTime = 5;
                }
                timer.Start();
                music.Play();
                music.Position = new TimeSpan(h, m, s);
                _playTimer.Start();
                if (!String.IsNullOrEmpty(switchMode) && ("1".Equals(switchMode) || "3".Equals(switchMode)) && switchTime > 0)
                {
                    music.Volume = 0;
                    switchInTimer.Start();

                }
                else
                {
                    music.Volume = Volume;
                }
            }
            else
            {
                music.Stop();
                cycleMode = currentProgram.CycleMode;

                MaxValue = 0;
                CheckBoxEnable = false;
                VolumeEnable = false;
            }
            //处理素材播放
            //处理删除了素材
            ObservableCollection<ProgramItem> sourceList = currentProgram.SourceList;
            ObservableCollection<ProgramItem> sourceList1 = WriteFileUtil.getSourceList(fileFullPath);
            List<ProgramItem> tempList1 = new List<ProgramItem>();
            if (null != sourceList1 && sourceList1.Count > 0)
            {
                List<string> sourceIds = new List<string>();
                foreach (ProgramItem programItem2 in sourceList1)
                {
                    sourceIds.Add(programItem2.No);
                }
                if (null != sourceList && sourceList.Count > 0)
                {
                    foreach (ProgramItem programItem1 in sourceList)
                    {
                        if (sourceIds.Contains(programItem1.No))
                        {
                            tempList1.Add(programItem1);
                        }
                    }
                }
            }

            if (null != tempList1 && tempList1.Count > 0)
            {

                ObservableCollection<ScreenVo> screenVos = WriteFileUtil.getScreenItemList();
                foreach (ProgramItem programItem1 in tempList1)
                {
                    ObservableCollection<ScreenItemVo> tempList = programItem1.ScreenItemVos;
                    ObservableCollection<ScreenItemVo> selectedScreenList = new ObservableCollection<ScreenItemVo>();
                    foreach (ScreenItemVo screenItem in tempList)
                    {
                        if (screenItem.IsSelected)
                        {
                            selectedScreenList.Add(screenItem);
                        }
                    }
                    programItem1.ScreenItemVos = selectedScreenList;
                }

                //先将素材分组，按屏幕，在按类型
                List<PlaySourceGroupVo> playSourceGroupVos = new List<PlaySourceGroupVo>();
                foreach (ScreenVo screen in screenVos)
                {
                    ObservableCollection<PlaySourceVo> playSourceVos = new ObservableCollection<PlaySourceVo>();
                    foreach (ProgramItem programItem2 in tempList1)
                    {
                        ObservableCollection<ScreenItemVo> tempScreenList = programItem2.ScreenItemVos;
                        if (null != tempScreenList && tempScreenList.Count > 0)
                        {
                            foreach (ScreenItemVo screenItem in tempScreenList)
                            {
                                if (screenItem.Id.Equals(screen.Id))
                                {
                                    PlaySourceVo playSourceVo = new PlaySourceVo();
                                    playSourceVo.Screen = screen;
                                    playSourceVo.SouceItem = programItem2;
                                    playSourceVo.Type = programItem2.ItemType.Equals("3") ? "2" : programItem2.ItemType;
                                    playSourceVos.Add(playSourceVo);
                                }
                            }
                        }
                    }
                    if (null != playSourceVos && playSourceVos.Count > 0)
                    {
                        var groupList = playSourceVos.GroupBy(s => s.Type);
                        List<PlaySourceItemVo> playSourceItemVos = new List<PlaySourceItemVo>();
                        foreach (var group1 in groupList)
                        {
                            PlaySourceItemVo playSourceItemVo = new PlaySourceItemVo();
                            playSourceItemVo.Type = group1.Key;
                            playSourceItemVo.PlaySourceVos = group1.ToList<PlaySourceVo>();
                            playSourceItemVos.Add(playSourceItemVo);
                        }
                        PlaySourceGroupVo playSourceGroupVo = new PlaySourceGroupVo();
                        playSourceGroupVo.Screen = screen;
                        playSourceGroupVo.Items = playSourceItemVos;
                        playSourceGroupVos.Add(playSourceGroupVo);
                    }
                }

                //处理资源播放
                if (null != playSourceGroupVos && playSourceGroupVos.Count > 0)
                {
                    DialogParameters parameters = null;
                    List<string> screenIds = new List<string>();
                    foreach (PlaySourceGroupVo playSourceGroupVo1 in playSourceGroupVos)
                    {
                        screenIds.Add(playSourceGroupVo1.Screen.Id + "");
                    }
                    foreach (PlaySourceGroupVo playSourceGroupVo in playSourceGroupVos)
                    {
                        ScreenVo screen = playSourceGroupVo.Screen;
                        if (null == openScreenIds || openScreenIds.Count == 0 || !openScreenIds.Contains(screen.Id + ""))
                        {
                            continue;
                        }
                        _eventAggregator.GetEvent<MonitorCleanUpEvent>().Publish(screenIds);
                        foreach (var item in playSourceGroupVo.Items)
                        {
                            PlaySourceNewVo playSourceNewVo = new PlaySourceNewVo();
                            playSourceNewVo.CycleModel = cycleMode;
                            playSourceNewVo.PlaySources = item.PlaySourceVos;
                            playSourceNewVo.ScreenIds = screenIds;
                            _eventAggregator.GetEvent<PlaySourceEvent>().Publish(playSourceNewVo);
                            if (null != monitorVos && monitorVos.Count > 0)
                            {
                                foreach (MonitorVo monitor in monitorVos)
                                {
                                    if (screen.Id == monitor.Screen.Id)
                                    {
                                        switch (monitor.Monitor)
                                        {
                                            case "Monitor":
                                                _eventAggregator.GetEvent<MonitorEvent>().Publish(playSourceNewVo);
                                                break;
                                            case "Monitor1":
                                                _eventAggregator.GetEvent<Monitor1Event>().Publish(playSourceNewVo);
                                                break;
                                            case "Monitor2":
                                                _eventAggregator.GetEvent<Monitor2Event>().Publish(playSourceNewVo);
                                                break;
                                            case "Monitor3":
                                                _eventAggregator.GetEvent<Monitor3Event>().Publish(playSourceNewVo);
                                                break;
                                            case "Monitor4":
                                                _eventAggregator.GetEvent<Monitor4Event>().Publish(playSourceNewVo);
                                                break;
                                        }
                                        break;
                                    }
                                }
                            }
                            /*
                            switch (item.Type)
                            {
                                case "1":
                                    //拿到新窗口的页面
                                    Window mp4Player = _containerExtension.Resolve<Mp4Player>();
                                    parameters.Add("screen", screen);
                                    parameters.Add("win", mp4Player);
                                    sourceWindowList.Add(mp4Player);
                                    //手动指定新窗口的viewModel
                                    mp4Player.DataContext = new Mp4PlayerViewModel(parameters,_eventAggregator);
                                    if (mp4Player.Owner == null)
                                        mp4Player.Owner = Application.Current?.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
                                    mp4Player.ShowInTaskbar = false;
                                    mp4Player.Top = Convert.ToDouble(screen.OrignY);
                                    mp4Player.Left = Convert.ToDouble(screen.OrignX);
                                    mp4Player.Width = Convert.ToDouble(screen.Width);
                                    mp4Player.Height = Convert.ToDouble(screen.Height);
                                    mp4Player.Show();
                                    break;
                                case "2":
                                    //拿到新窗口的页面
                                    Window imagePlayer1 = _containerExtension.Resolve<ImagePlayer>();
                                    sourceWindowList.Add(imagePlayer1);
                                    imagePlayer1.DataContext = new ImagePlayerViewModel(parameters, _eventAggregator);
                                    //手动指定新窗口的viewModel
                                    if (imagePlayer1.Owner == null)
                                        imagePlayer1.Owner = Application.Current?.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
                                    imagePlayer1.ShowInTaskbar = false;
                                    imagePlayer1.Top = Convert.ToDouble(screen.OrignY);
                                    imagePlayer1.Left = Convert.ToDouble(screen.OrignX);
                                    imagePlayer1.Width = Convert.ToDouble(screen.Width);
                                    imagePlayer1.Height = Convert.ToDouble(screen.Height);
                                    imagePlayer1.Show();
                                    break;
                                case "4":
                                    //网页框

                                    //拿到新窗口的页面

                                    Window webBrowser = _containerExtension.Resolve<WebBrowserView>();
                                    webBrowser.DataContext = new WebBrowserViewModel(parameters, _eventAggregator);
                                    sourceWindowList.Add(webBrowser);
                                    //手动指定新窗口的viewModel
                                    if (webBrowser.Owner == null)
                                        webBrowser.Owner = Application.Current?.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
                                    webBrowser.ShowInTaskbar = false;

                                    webBrowser.Top = Convert.ToDouble(screen.OrignY);
                                    webBrowser.Left = Convert.ToDouble(screen.OrignX);
                                    webBrowser.Width = Convert.ToDouble(screen.Width);
                                    webBrowser.Height = Convert.ToDouble(screen.Height);
                                    webBrowser.Show();

                                    break;
                                default:
                                    break;

                            }*/
                        }
                    }
                }
                else
                {
                    _eventAggregator.GetEvent<ClearPlaySourceEvent>().Publish();
                }
            }
            else
            {
                //_eventAggregator.GetEvent<PlayStatusEvent>().Publish("-2");
                _eventAggregator.GetEvent<ClearPlaySourceEvent>().Publish();
            }
            _eventAggregator.GetEvent<PlayProgramEvent>().Publish(programItemGroupVo);

        }

        ObservableCollection<ProgramItemVo> initTempList = new ObservableCollection<ProgramItemVo>();
        private void initList()
        {
            // ProgramItems.Clear();
            if (null != program)
            {
                fileFullPath = program.FilePath + "\\" + program.Name + ".info"; // 指定要创建的文件路径及名称
                try
                {
                    if (!File.Exists(fileFullPath))
                    {
                        MessageBox.Show("文件不存在！");
                        return;
                    }
                    string content = WriteFileUtil.readFile(fileFullPath);
                    if (!String.IsNullOrEmpty(content))
                    {
                        JObject programJson = JsonConvert.DeserializeObject<JObject>(content);
                        if (programJson.ContainsKey("programItems"))
                        {
                            initTempList = JsonConvert.DeserializeObject<ObservableCollection<ProgramItemVo>>((String)programJson.GetValue("programItems"));
                        }
                    }



                }
                catch (Exception ex)
                {

                }

            }
        }



        public ObservableCollection<ProgramVo> ProgramVos { get { return programVos; } set { this.programVos = value; RaisePropertyChanged(); } }

        public ProgramItemVo SelectedItem { get { return this.selectedItem; } set { this.selectedItem = value; RaisePropertyChanged(); } }

        public int SelectedIndex { get { return this.selectedIndex; } set { this.selectedIndex = value; RaisePropertyChanged(); } }

        public ObservableCollection<ProgramItemVo> ProgramItems { get { return programItems; } set { this.programItems = value; RaisePropertyChanged(); } }


        public string CurrentMusic { get { return currentMusic; } set { this.currentMusic = value; RaisePropertyChanged(); } }

        public string MusicSrc { get { return musicSrc; } set { this.musicSrc = value; RaisePropertyChanged(); } }

        public double StartWith { get { return startWith; } set { this.startWith = value; RaisePropertyChanged(); } }

        public int MaxValue { get { return maxValue; } set { this.maxValue = value; RaisePropertyChanged(); } }

        public ObservableCollection<ProgramItemVo> CurrentList { get { return currentList; } set { this.currentList = value; RaisePropertyChanged(); } }

        public double Volume { get { return volume; } set { this.volume = value; RaisePropertyChanged(); } }

        public string PlayText { get { return playText; } set { this.playText = value; RaisePropertyChanged(); } }

        public string CurrentTimeStr { get { return currentTimeStr; } set { this.currentTimeStr = value; RaisePropertyChanged(); } }

        public double TestVolume { get { return testVolume; } set { this.testVolume = value; RaisePropertyChanged(); } }

        public double EndWith { get { return endWith; } set { this.endWith = value; RaisePropertyChanged(); } }

        public bool IsEnabled { get { return isEnabled; } set { this.isEnabled = value; RaisePropertyChanged(); } }

        public bool IsPauseEnabled { get { return isPauseEnabled; } set { this.isPauseEnabled = value; RaisePropertyChanged(); } }

        public bool PlayFlag { get { return playFlag; } set { this.playFlag = value; RaisePropertyChanged(); } }

        public bool VolumeEnable { get { return volumeEnable; } set { this.volumeEnable = value; RaisePropertyChanged(); } }
        public bool CheckBoxEnable { get { return checkBoxEnable; } set { this.checkBoxEnable = value; RaisePropertyChanged(); } }

        public bool IsDisplay { get { return isDisplay; } set { this.isDisplay = value; RaisePropertyChanged(); } }

        public MediaElement Music { get => music; set => music = value; }
    }
}
